﻿package tools;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.Date;

/**
 * 从文件中读取Object，或者将Object写入文件中，实现Java的对象序列化操作
 * @version 1.5
 * 
 * @author Lanjun ZHOU
 * 
 */
public class ObjectTools {
	public static Object readFromFile(String filename) {
		return readFromFile(new File(filename));
	}

	public static Object readFromFile(File file) {
		ObjectInputStream in;
		Object obj = null;
		System.err.println("----------\nReading Object from File: " + file.getAbsolutePath());
		try {
			in = new ObjectInputStream(new FileInputStream(file));
			obj = in.readObject();
			in.close();
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		}
		System.err.println("Done!\n----------");
		return obj;
	}

	public static void writeToFile(Object obj, String filename) {
		writeToFile(obj, new File(filename));
	}

	public static void writeToFile(Object obj, File file) {
		File dir = file.getParentFile();
		if(!dir.exists()) {
			dir.mkdirs();
		}
		System.err.println("----------\nWriting Object to File: " + file.getAbsolutePath());
		try {
			ObjectOutputStream out = new ObjectOutputStream(
					new FileOutputStream(file));
			out.writeObject(obj);
			out.close();
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		System.err.println("Done!\n----------" + (new Date()).toString());
	}
}
